package com.mstarc.app.mnfc;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.mstarc.app.mnfc.mstarcApiUtils.ApduUtil;
import com.mstarc.app.mnfc.mstarcApiUtils.BytetohexStringUtil;
import com.mstarc.app.mnfc.mstarcApiUtils.InitSEIDUtil;
import com.mstarc.app.mnfc.mstarcApiUtils.InitializeUtil;
import com.mstarc.app.mnfc.mstarcApiUtils.MstarcResetUtil;
import com.mstarc.app.mnfc.mstarcApiUtils.StringAndByteUtil;
import com.mstarc.app.mnfc.okhttp.OKHttpResult;
import com.mstarc.app.mnfc.okhttp.OkHttpRequest;

import mstarc_os_api.mstarc_os_api_msg;

/**
 * @author 崔健伟
 * @version V1.0
 * @Title: ApduService.java
 * @Package com.mstarc.app.mnfc
 * @Description:
 * @date 2017/8/8 08:58
 */
public class ApduService extends Service implements OKHttpResult {
    public static final String APDUSERVICE_ACTION = "startAction";
    public static final String ISPERSONALIZE = "isPersonalize";
    public static final String TYPE_INT = "mTypeInt";
    private static final String IP1 = "http://natapp.qdyouke.com/GetApduList.aspx?";
    private static final String LASTAPDU = "&lastApdu=";//最后一次请求的apdu指令
    private static final String LASTDATA = "&lastData=";
    private static final String APDUNUM = "&apduSum=";
    private static final String LASTAPDUSW = "&lastApduSw=";
    private static final String SEID_STR = "&seId=";
    private static final String RESET = "reset";
    private static final String RETURN_ALL = "returnall";

    private String URL = "";//网络请求的接口地址前缀
    private String mLastApdu = "";//每次请求执行的最后一条apdu指令
    private int apduSum = 0;//apdu请求中9000的个数
    private String lastData = "";
    private int[] lastApduSw = new int[2];

    private MyBroadcast myBroadcast;
    private String seid = "";//seid
    private mstarc_os_api_msg m_api_msg;
    private int count = 0;//记录第几次网络请求
    int[] secondApdu = new int[]{0x00, 0xc0, 0x00, 0x00, 0x00};
    private boolean needAddAll = false;
    private Context mContext;
    private int reRequestCount = 0;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
        m_api_msg = InitializeUtil.getInstance(mContext).getM_api_msg();
        myBroadcast = new MyBroadcast();
        initBroad(true);
    }

    @Override
    public void onDestroy() {
        initBroad(false);
        startLog("Service状态：", "关闭！");
        super.onDestroy();
    }

    private void initBroad(boolean b) {
        if (b) {
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(APDUSERVICE_ACTION);
            registerReceiver(myBroadcast, intentFilter);
        } else {
            unregisterReceiver(myBroadcast);
        }
    }

    class MyBroadcast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            getIntent(intent);
        }
    }

    private void getIntent(Intent intent) {
        if (intent != null) {
            readyHttp();
        } else {
            startLog("参数传递：", "参数有误！");
        }
    }

    private void readyHttp() {
        reRequestCount = 0;
        if (!InitializeUtil.getInstance(mContext).isHasInit()) {
            InitializeUtil.getInstance(mContext).init(m_api_msg);
        }
        initHttp();
    }

    private void logIntArray(int[] intArray, String tagTitle) {
        LogUtil.logIntArray(intArray, tagTitle);
    }

    private void startLog(String logTitle, String logContent) {
        LogUtil.startLog(logTitle, logContent);
    }

    /**
     * 获取seid
     */
    private void initSeid() {
        int[] nfc_buf = InitSEIDUtil.initSEID(m_api_msg);
        if (nfc_buf != null) {
            logIntArray(nfc_buf, "Code:");
            seid = StringAndByteUtil.intArrayToHexString(InitSEIDUtil.getSEID(nfc_buf));
            startLog("seidForHex：", seid);
        } else {
            startLog("seidForHex：", "获取SEID失败！");
        }
    }

    private void initHttp() {
        if (seid.equals("")) {
            initSeid();
        }
        URL = IP1
                + SEID_STR + seid
                + LASTAPDU + mLastApdu
                + LASTDATA + lastData
                + APDUNUM + apduSum
                + LASTAPDUSW + StringAndByteUtil.intArrayToHexString(lastApduSw);
        startLog("URL：", URL);
        OkHttpRequest.getInstance(this).getHttp(URL, 1);
    }

    @Override
    public void requestJsonOnError(int msgFlag) {
        startLog("请求状态：", "requestJsonOnError");
    }

    @Override
    public void requestJsonOnSucceed(String json, int msgFlag) {
        switch (msgFlag) {
            case 1:
                toNext(json);
                break;
        }
    }

    @Override
    public void requestJsonOnLocalError(int msgFlag) {
        startLog("请求状态：", "requestJsonOnLocalError");
    }

    /**
     * 重置nfc
     */
    private void toReset() {
        int[] nfc_reset_buf = MstarcResetUtil.reset(m_api_msg);
        if (nfc_reset_buf != null)
            logIntArray(nfc_reset_buf, "重置:");
    }

    private void toNext(String json) {
        Log.d("MainActivity", count + "：" + "requestJsonOnSucceed: " + json);
        needAddAll = false;
        int[] result = new int[0];
        ApduEntity apduEntity = getTByJsonString(json, ApduEntity.class);
        if (apduEntity != null) {
            if (apduEntity.getState() == 0) {
                initParams();
                if (apduEntity.getApduList() != null && apduEntity.getApduList().size() != 0) {
                    int removeCount = 0;
                    for (int i = 0; i < apduEntity.getApduList().size(); i++) {
                        String lastApdu = apduEntity.getApduList().get(i);
                        if (lastApdu.equals(RESET)) {
                            int[] nfc_reset_buf = MstarcResetUtil.reset(m_api_msg);
                            if (nfc_reset_buf != null) {
                                logIntArray(nfc_reset_buf, count + "：" + "条数：" + (i + 1) + "：" + "重置:");
                                result = new int[]{0x90, 0x00};
                            }
                        } else if (lastApdu.equals(RETURN_ALL)) {
                            needAddAll = true;
                            continue;
                        } else {
                            result = ApduUtil.apdu(m_api_msg, StringAndByteUtil.getInt(lastApdu));
                            logIntArray(StringAndByteUtil.getInt(lastApdu), count + "：" + "条数：" + (i + 1) + "参数1：");
                            if (result != null) {
                                logIntArray(result, count + "：" + "条数：" + (i + 1) + "结果1：");
                            }
                            if (is0x61BL(result)) {
                                secondApdu[secondApdu.length - 1] = result[result.length - 1];
                                logIntArray(secondApdu, count + "：" + "条数：" + (i + 1) + "参数2：");
                                result = ApduUtil.apdu(m_api_msg, secondApdu);
                                result = is0x61(result);
                                if (result != null) {
                                    logIntArray(result, count + "：" + "条数：" + (i + 1) + "结果2：");
                                }
                            }
                            if (is0x6c(result)) {
                                int[] params = StringAndByteUtil.getInt(lastApdu);
                                params[params.length - 1] = result[result.length - 1];
                                logIntArray(params, count + "：" + "条数：" + (i + 1) + " 6c参数：");
                                result = ApduUtil.apdu(m_api_msg, params);
                                if (result != null) {
                                    logIntArray(result, count + "：" + "条数：" + (i + 1) + "6c结果：");
                                }
                            }
                            if (needAddAll) {
                                lastData += StringAndByteUtil.intArrayToHexString(getResultData(result, removeCount)) + ";";
                            } else {
                                lastData = StringAndByteUtil.intArrayToHexString(getResultData(result, removeCount));
                            }
                            mLastApdu = apduEntity.getApduList().get(i);
                            if (result.length >= 2 && result[result.length - 2] == 0x90 && result[result.length - 1] == 0x00) {
                                apduSum++;
                            } else {
                                break;
                            }
                        }
                    }
//                    if (result.length % 2 == 0) {
                    if (result.length >= 2) {
                        lastApduSw[0] = result[result.length - 2];
                        lastApduSw[1] = result[result.length - 1];
                        String url1 = "";
                        if (needAddAll) {
                            lastData = lastData.substring(0, lastData.length() - 1);
                        }
                        startLog("mLastApdu：", mLastApdu);
                        initHttp();
                    } else {
                        startLog("请求结果：", "请求结果为空！");
                    }
//                    } else {
//                        startLog("apdu结果：", "请求结果不合法！");
//                    }
                } else {
                    startLog("请求状态：", "数组为空！");
                }
            } else if (apduEntity.getState() == 2) {
                startLog("请求状态：", "请求结束！");
            } else {
                startLog("请求状态：", "请求失败！");
//                if (reRequestCount < 2) {
//                    reRequestCount++;
//                    initHttp();
//                }
            }
        } else {
            startLog("请求状态：", "请求失败！");
        }

    }

    private void initParams() {
        apduSum = 0;
        count++;
        lastData = "";
        lastApduSw = new int[2];
    }

    private boolean is0x61BL(int[] result) {
        if (result.length >= 2 && result[result.length - 2] == 0x61) {
            return true;
        }
        return false;
    }

    private int[] is0x61(int[] result) {
        if (result.length >= 2 && result[result.length - 2] == 0x61) {
            result = nextResult(result);
        }
        return result;
    }

    private boolean is0x6c(int[] result) {
        if (result[result.length - 2] == 0x6c) {
            return true;
        }
        return false;
    }

    private int[] nextResult(int[] result) {
        secondApdu[secondApdu.length - 1] = result[result.length - 1];
        logIntArray(secondApdu, "第二次请求参数：");
        int[] nextResult = ApduUtil.apdu(m_api_msg, secondApdu);
        if (nextResult != null) {
            logIntArray(nextResult, "第二次请求结果：");
        } else {
            startLog("结果：", "为空！");
        }
        return nextResult;
    }

    private int[] getResultData(int[] data, int removeCount) {
        if (data.length >= removeCount) {
            int[] datas = new int[data.length - removeCount];
            for (int i = 0; i < datas.length; i++) {
                datas[i] = data[i];
            }
            return datas;
        }
        return new int[0];
    }

    @SuppressWarnings("unchecked")
    protected <T> T getTByJsonString(String str, Class<?> clas) {
        return (T) JSON.parseObject(str, clas);
    }
}
